package com.neiquan.backstage.user.web.action;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.neiquan.backstage.common.util.BackendErrorCode;
import com.neiquan.backstage.common.util.CommonResp;
import com.neiquan.backstage.common.util.Configs;
import com.neiquan.backstage.common.util.ExtraSpringHibernateTemplate;
import com.neiquan.backstage.common.util.SMSUtil;
import com.neiquan.backstage.common.util.Sessions;
import com.neiquan.backstage.common.util.SimpleErrorCode;
import com.neiquan.backstage.common.util.Strings;
import com.neiquan.backstage.platform_weixin.web.action.PlatformWeixinAction;
import com.neiquan.backstage.pub.bsc.dao.po.Entrepreneur;
import com.neiquan.backstage.pub.bsc.dao.po.PlatformAllianceMember;
import com.neiquan.backstage.pub.bsc.dao.po.User;
import com.neiquan.backstage.resourec_manage.EntrepreneurService;
import com.neiquan.backstage.user.UserService;

import me.chanjar.weixin.common.util.http.URIUtil;
import net.sf.json.JSONObject;

@Controller
@RequestMapping(value = "user", produces = { "text/json;charset=UTF-8" })
public class UserAction {
	private static final Logger log = LoggerFactory.getLogger(PlatformWeixinAction.class);
	private static Class<?> poc = User.class;
	private static Class<?> pocM = PlatformAllianceMember.class;
	@Autowired
	private ExtraSpringHibernateTemplate extraSpringHibernateTemplate;
	@Autowired
	private UserService userService;
	@Autowired
	private EntrepreneurService entrepreneurService;
	
	/*
	@ResponseBody
	@RequestMapping(value = "editMyInfo")
	public String edit(Integer userId, String name, String phone, String entrepreneurName, String password, String post, String department) {
		User toUpdate = userService.queryById(userId);
		if (null == toUpdate) {
			return CommonResp.buildErrorResp(BackendErrorCode.not_exist).toJsonString();
		}
		if (StringUtils.isNoneBlank(phone) && !phone.equals(toUpdate.getPhone()) && userService.queryByPhone(phone, toUpdate.getMemberId()) != null) {
			return CommonResp.buildErrorResp("手机号已存在").toJsonString();
		}
		Integer memberId = toUpdate.getMemberId();
		Entrepreneur entityE = entrepreneurService.queryByUniqueId(toUpdate.getEntrepreneurUniqueId(), memberId);
		if (toUpdate.getType() == 1 && !entityE.getName().equals(entrepreneurName) && entrepreneurService.queryByName(entrepreneurName, memberId) != null) {
			return CommonResp.buildErrorResp("公司名称已存在").toJsonString();
		}
		if (StringUtils.isNoneBlank(name)) {
			toUpdate.setName(Strings.trimAndNotNull(name));
		}
		if (StringUtils.isNoneBlank(department)) {
			toUpdate.setDepartment(Strings.trimAndNotNull(department));
		}
		if (StringUtils.isNoneBlank(post)) {
			toUpdate.setPost(Strings.trimAndNotNull(post));
		}
		if (StringUtils.isNoneBlank(phone)) {
			toUpdate.setPhone(Strings.trimAndNotNull(phone));
		}
		if (StringUtils.isNoneBlank(password)) {
			toUpdate.setPassword(Strings.trimAndNotNull(password));
		}
		if (toUpdate.getType() == 1 && !entityE.getName().equals(entrepreneurName)) {
			toUpdate.setEntrepreneurName(entrepreneurName);
			entityE.setName(entrepreneurName);
		}
		extraSpringHibernateTemplate.getHibernateTemplate().update(entityE);
		extraSpringHibernateTemplate.getHibernateTemplate().update(toUpdate);
		return CommonResp.buildSuccessResp().toJsonString();
	}

	*/
	
	/**
	 * 编辑
	 * 
	 * @param id
	 * @param name
	 * @param phone
	 * @param entrepreneurName
	 * @param password
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "editMyInfo")
	public String edit(Integer userId, String name, String phone, String entrepreneurName, String password, String post, String department) {
		User toUpdate = userService.queryById(userId);
		if (null == toUpdate) {
			return CommonResp.buildErrorResp(BackendErrorCode.not_exist).toJsonString();
		}
		if (StringUtils.isNoneBlank(phone) && !phone.equals(toUpdate.getPhone()) && userService.queryByPhone(phone, toUpdate.getMemberId()) != null) {
			return CommonResp.buildErrorResp("手机号已存在").toJsonString();
		}
		if (StringUtils.isNoneBlank(name)) {
			toUpdate.setName(Strings.trimAndNotNull(name));
		}
		if (StringUtils.isNoneBlank(department)) {
			toUpdate.setDepartment(Strings.trimAndNotNull(department));
		}
		if (StringUtils.isNoneBlank(post)) {
			toUpdate.setPost(Strings.trimAndNotNull(post));
		}
		if (StringUtils.isNoneBlank(phone)) {
			toUpdate.setPhone(Strings.trimAndNotNull(phone));
		}
		if (StringUtils.isNoneBlank(password)) {
			toUpdate.setPassword(Strings.trimAndNotNull(password));
		}
		extraSpringHibernateTemplate.getHibernateTemplate().update(toUpdate);
		return CommonResp.buildSuccessResp().toJsonString();
	}

	/**
	 * 通过
	 * 
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "pass")
	public String pass(Integer id) {
		User toUpdate = userService.queryById(id);
		if (toUpdate == null) {
			return CommonResp.buildErrorResp(BackendErrorCode.not_exist).toJsonString();
		}
		if (toUpdate.getStatus() != User.STATUS_WAIT) {
			return CommonResp.buildErrorResp(BackendErrorCode.status_error).toJsonString();
		}
		toUpdate.setStatus(User.STATUS_PASS);
		extraSpringHibernateTemplate.getHibernateTemplate().update(toUpdate);
		return CommonResp.buildSuccessResp().toJsonString();
	}

	/**
	 * 拒绝
	 * 
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "reject")
	public String reject(Integer id, String remark) {
		User toUpdate = userService.queryById(id);
		if (toUpdate == null) {
			return CommonResp.buildErrorResp(BackendErrorCode.not_exist).toJsonString();
		}
		if (toUpdate.getStatus() != User.STATUS_WAIT) {
			return CommonResp.buildErrorResp(BackendErrorCode.status_error).toJsonString();
		}
		toUpdate.setRemark(remark);
		toUpdate.setStatus(User.STATUS_REJECT);
		extraSpringHibernateTemplate.getHibernateTemplate().update(toUpdate);
		return CommonResp.buildSuccessResp().toJsonString();
	}

	/**
	 * 删除
	 * 
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "remove")
	public String remove(Integer id) {
		User toDelete = userService.queryById(id);
		if (toDelete == null) {
			return CommonResp.buildErrorResp(BackendErrorCode.not_exist).toJsonString();
		}
		extraSpringHibernateTemplate.getHibernateTemplate().delete(toDelete);
		return CommonResp.buildSuccessResp().toJsonString();
	}

	@ResponseBody
	@RequestMapping(value = "edit")
	public String edit(Integer userId, String name, String phone, String password, String department, String post) {
		User toUpdate = extraSpringHibernateTemplate.findFirstOneByPropEq(poc, "userId", userId);
		if (StringUtils.isNoneBlank(password)) {
			toUpdate.setPassword(password);
		}
		if (StringUtils.isNoneBlank(phone)) {
			toUpdate.setPhone(phone);
		}
		if (StringUtils.isNoneBlank(name)) {
			toUpdate.setName(name);
		}
		if (StringUtils.isNoneBlank(department)) {
			toUpdate.setDepartment(department);
		}
		if (StringUtils.isNoneBlank(post)) {
			toUpdate.setPost(post);
		}
		extraSpringHibernateTemplate.getHibernateTemplate().update(toUpdate);
		return CommonResp.buildSuccessResp().toJsonString();
	}

	/**
	 * 微信绑定用户
	 * 
	 * @param phone
	 *            用户注册手机
	 * @param password
	 *            用户登陆密码
	 * @param memberId
	 *            用户区号
	 * @param session
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "bindinAccount")
	public String bindinAccount(String phone, String password, Integer memberId, HttpSession session, HttpServletResponse response) throws IOException {
		response.setContentType("text/html;charset=utf-8");
		if (StringUtils.isBlank(phone)) {
			return "redirect:../../bindinaccount.jsp?memberId=" + memberId + "&message=手机号码不能为空";
		}
		if (StringUtils.isBlank(password)) {
			return "redirect:../../bindinaccount.jsp?memberId=" + memberId + "&message=密码不能为空";
		}
		User toCheck = userService.queryByPhone(phone, memberId);
		if (toCheck == null) {
			return "redirect:../../bindinaccount.jsp?memberId=" + memberId + "&message=您的姓名和登记的手机号不匹配";
		}
		if (!password.equals(toCheck.getPassword())) {
			return "redirect:../../bindinaccount.jsp?memberId=" + memberId + "&message=您的姓名和登记的手机号不匹配";
		}
		String state = phone + "," + memberId;
		/**
		 * 向微信发起请求获取一个用户手机端的code值 回掉一个函数 参数需要一个客户端appid
		 * 
		 */
		PlatformAllianceMember platformAllianceMember = extraSpringHibernateTemplate.findFirstOneByPropEq(pocM, "memberId", memberId);
		String project_name = Configs.get().getString("system.project_name");
		String redirect_uri = String.format("%s/%s/api/user/getCode?memberId=%d", platformAllianceMember.getWebsite(), project_name, memberId);
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?";
		url += "appid=" + platformAllianceMember.getWeixinAppId();
		url += "&redirect_uri=" + URIUtil.encodeURIComponent(redirect_uri);
		url += "&response_type=code";
		url += "&scope=snsapi_userinfo";
		url += "&state=" + state;
		url += "#wechat_redirect";
		return "redirect:" + url;
	}

	@RequestMapping(value = "getCode")
	public String getCode(HttpServletRequest request, String code, String state, HttpSession session) throws IOException {
		String[] split = state.split(",");
		String phone = split[0];
		int memberId = Integer.parseInt(split[1]);
		PlatformAllianceMember platformAllianceMember = extraSpringHibernateTemplate.findFirstOneByPropEq(pocM, "memberId", memberId);
		String weixinAppId = platformAllianceMember.getWeixinAppId();
		String weixinAppSecret = platformAllianceMember.getWeixinAppSecret();
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + weixinAppId + "&secret=" + weixinAppSecret + "&code=" + code + "&grant_type=authorization_code";
		URL url2 = new URL(url);
		HttpURLConnection connection = (HttpURLConnection) url2.openConnection();
		connection.connect();
		InputStream inputStream = connection.getInputStream();
		Reader reader = new InputStreamReader(inputStream, "UTF-8");
		BufferedReader bufferedReader = new BufferedReader(reader);
		String str = null;
		StringBuffer sb = new StringBuffer();
		while ((str = bufferedReader.readLine()) != null) {
			sb.append(str);
		}
		JSONObject json = JSONObject.fromObject(sb.toString());
		String openId = (String) json.get("openid");
		User toUpdate = userService.queryByPhone(phone, memberId);
		toUpdate.setWeixin_openid(openId);
		extraSpringHibernateTemplate.getHibernateTemplate().update(toUpdate);
		connection.disconnect();
		if (toUpdate.getStatus() == 2) {
			return "redirect:../../checking.jsp";
		}
		if (toUpdate.getStatus() == 1) {
			Sessions.setLoginedUser(toUpdate, session);
			return "redirect:../../myworkaddr.jsp";
		}
		return "redirect:../../checkfial.jsp";
	}

	@ResponseBody
	@RequestMapping(value = "add")
	public String add(String passwordr, Integer type, String name, String entrepreneurName, String phone, String password, Integer memberId, HttpSession session) {
		/**
		 * 验证码验证 if(StringUtils.isBlank(smsCode)){ return
		 * CommonResp.buildErrorResp("验证不能为空").toJsonString(); } String
		 * sendsmsCode = (String) session.getAttribute("smsCode");
		 * System.out.println(sendsmsCode); if(!smsCode.equals(sendsmsCode)){
		 * return CommonResp.buildErrorResp("验证码不正确").toJsonString(); }
		 * session.removeAttribute("smsCode");
		 */
		if (StringUtils.isBlank(entrepreneurName)) {
			return CommonResp.buildErrorResp(BackendErrorCode.missing_parameter).toJsonString();
		}
		if (StringUtils.isBlank(passwordr)) {
			return CommonResp.buildErrorResp(BackendErrorCode.missing_parameter).toJsonString();
		}
		if (StringUtils.isBlank(name)) {
			return CommonResp.buildErrorResp(BackendErrorCode.missing_parameter).toJsonString();
		}
		if (StringUtils.isBlank(phone)) {
			return CommonResp.buildErrorResp(BackendErrorCode.missing_parameter).toJsonString();
		}
		if (StringUtils.isBlank(password)) {
			return CommonResp.buildErrorResp(BackendErrorCode.missing_parameter).toJsonString();
		}
		if (!password.equals(passwordr)) {
			return CommonResp.buildErrorResp(SimpleErrorCode.buildError("密码不一致")).toJsonString();
		}
		if (password.length() < 6 || password.length() > 20) {
			return CommonResp.buildErrorResp(SimpleErrorCode.buildError("密码过短或过长")).toJsonString();
		}
		User toSave = new User();
		if (type == 1) {
			Entrepreneur entrepreneur = entrepreneurService.queryByName(entrepreneurName, memberId);
			if (entrepreneur != null) {
				return CommonResp.buildErrorResp(SimpleErrorCode.buildError("公司名称已存在")).toJsonString();
			}
			String randomUUID = UUID.randomUUID().toString();
			toSave.setEntrepreneurUniqueId(randomUUID);
		}
		if (userService.queryByPhone(phone, memberId) != null) {
			return CommonResp.buildErrorResp(SimpleErrorCode.buildError("手机号已存在")).toJsonString();
		}
		if (type != 1) {
			Entrepreneur entrepreneur = entrepreneurService.queryByName(entrepreneurName, memberId);
			String randomUUID = entrepreneur.getUniqueId();
			toSave.setEntrepreneurUniqueId(randomUUID);
		}
		toSave.setMemberId(memberId);
		toSave.setDtCreat(System.currentTimeMillis());
		toSave.setEntrepreneurName(entrepreneurName);
		toSave.setName(name);
		toSave.setPassword(password);
		toSave.setPhone(phone);
		toSave.setType(type);
		toSave.setStatus(User.STATUS_WAIT);
		extraSpringHibernateTemplate.getHibernateTemplate().save(toSave);
		return CommonResp.buildSuccessResp().toJsonString();
	}

	/**
	 * 获取验证码
	 */
	@ResponseBody
	@RequestMapping(value = "smsVerify")
	public String smsVerify(String phone, HttpSession session) throws Exception {
		if (StringUtils.isBlank(phone)) {
			return CommonResp.buildErrorResp("手机号不能为空").toJsonString();
		}
		String str = "";
		for (int i = 0; i < 6; i++) {
			String a = (int) (Math.random() * 10) + "";
			str += a;
		}
		SMSUtil.batchSend(phone, "亲爱的用户，您的验证码是" + str + "，5分钟内有效。");
		session.setAttribute("smsCode", str);
		return CommonResp.buildSuccessResp().toJsonString();
	}

}
